package togoogle.common;

import java.util.logging.Logger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;
/**
 * 宸ュ叿绫�
 * 1銆佺粰浼犻�鐨勫弬鏁板姞瀵�
 * 2銆佹ā鎷焢ost璇锋眰锛屼紶閫掑弬鏁帮紝寰楀埌杩斿洖缁撴灉
 * 3銆佷粠鍥炶皟URL鐨勫弬鏁颁腑鑾峰緱visitor_nick鍊硷紝鍗硁ick
 * @author TOP
 *
 */
public class Util {
	 private static final Logger log = Logger.getLogger("Util"); 
	/*
	 * 浜岃鍒惰浆瀛楃涓�
	 */
	private static String byte2hex(byte[] b) {

		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/*
	 * 鎶婄粡杩嘊ASE64缂栫爜鐨勫瓧绗︿覆杞崲涓篗ap瀵硅薄
	 */
	public static Map<String, String> convertBase64StringtoMap(String str) throws Base64DecoderException {

		if (str == null)
			return null;
		String keyvalues = null;
		keyvalues = new String(Base64.decode(str));
		log.info(keyvalues);
		if (keyvalues == null || keyvalues.length() == 0)
			return null;
		String[] keyvalueArray = keyvalues.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String keyvalue : keyvalueArray) {
			String[] s = keyvalue.split("=");
			if (s == null || s.length != 2)
				return null;
			map.put(s[0], s[1]);
		}
		return map;
	}

	/*
	 * 绛惧悕鏂规硶锛岀敤浜庣敓鎴愮鍚嶃�
	 * 
	 * @param params 浼犵粰鏈嶅姟鍣ㄧ殑鍙傛暟
	 * 
	 * @param secret 鍒嗛厤缁欐偍鐨凙PP_SECRET
	 */
	public static String sign(TreeMap<String, String> params, String secret) {

		String result = null;
		if (params == null)
			return result;
		Iterator<String> iter = params.keySet().iterator();
		StringBuffer orgin = new StringBuffer(secret);
		while (iter.hasNext()) {
			String name = (String) iter.next();
			orgin.append(name).append(params.get(name));
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception ex) {
			throw new java.lang.RuntimeException("sign error !");
		}
		return result;
	}

	/**
	 * 妯℃嫙post璇锋眰锛岃皟鐢╝pi锛屼紶閫掑弬鏁帮紝鑾峰緱缁撴灉
	 * @param urlStr 璇锋眰鐨剈rl
	 * @param content 浼犻�鐨勫弬鏁�
	 * @return 璋冪敤api鑾峰緱杩斿洖缁撴灉
	 */
	public static String getResult(String urlStr, String content) {
		URL url = null;
		HttpURLConnection connection = null;

		try {
			//寤虹珛杩炴帴
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.connect();

			//浼犻�鍙傛暟
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			//鐢╱tf-8鐨勭紪鐮佹柟寮忎紶閫掑弬鏁帮紝鍚﹀垯涓枃浼氬嚭鐜颁贡鐮�
			out.write(content.getBytes("utf-8"));
			out.flush();
			out.close();

			//鑾峰緱杩斿洖缁撴灉
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection
					.getInputStream(), "utf-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
	
	/**
	 * 鏍规嵁鍥炶皟url涓殑top_parameters鑾峰緱nick
	 * @param top_parameters 鍥炶皟url涓殑鍙傛暟
	 * @return nick
	 * @throws Base64DecoderException 
	 */
    public static String ParametersName(String top_parameters) throws Base64DecoderException{

        String nick=null; 
        Map<String, String> map= convertBase64StringtoMap(top_parameters); 
        Iterator keyValuePairs = map.entrySet().iterator(); 
        for (int i = 0; i < map.size(); i++) 
        { 
	        Map.Entry entry = (Map.Entry) keyValuePairs.next(); 
	        Object key = entry.getKey(); 
	        Object value = entry.getValue(); 
	        if(key.equals("visitor_nick")){
	
	            nick=(String) value; 
	        } 
        } 

        return nick; 

    }
    public static boolean validateSign(String sign, String parameter, String secret){
    	 MessageDigest md = null;
    	 try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	 byte[] digest = md.digest((parameter + secret).getBytes());
    	 String result=Base64.encode(digest);
    	 log.info("top_sign:"+sign);
    	 log.info("sign:"+result);
    	 return sign!= null && parameter != null && secret != null&& sign.equals(result);
    	
    }
}
